<?php

namespace IDock\Insurance\DAJIA\Request;

use Exception;
use IDock\Insurance\DAJIA\DAJIAEnums;
use IDock\Insurance\DAJIA\Request\AllDAJIARequest;
use IDock\Insurance\DAJIA\Response\CommonResponse;
use IDock\Insurance\DAJIA\Response\InsuranceOrderQueryResponse;
use IDock\Insurance\DAJIA\Response\InsurancePriceQueryResponse;
use IDock\Visitor\NonCar\NonCarProductVisitor;
use IDock\Visitor\Premium\PremiumChargingPileVisitor;
use IDock\Visitor\Premium\PremiumCoverageVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;

/**
 * 查询保单接口
 */
class InsurancePriceQueryRequest extends AllDAJIARequest
{
    protected $code = 'ODR1009';

    protected $response = InsurancePriceQueryResponse::class;

    protected $urlTip = '保费计算';

    protected $orderNo = '';

    /**
     * @var PremiumInquiryVisitor $visitor
     */
    protected $visitor;

    public function generate(): array
    {
        $param = [
            'orderNo' => $this->visitor->getExtInfoVisitor()->argc['orderNo'] ?? '',
            'motorJointType' => $this->getMotorJointType(),
            'basePartReq' => $this->getBasePartReq(),
            'coverageList' => $this->getCoverageList(),
            'vehicleTaxation' => $this->getVehicleTaxation(),
            'vehicleInfo' => [],
            'nvhPolicyList' => $this->getNoCarInfo(),
            'chargingPostList' => $this->getChargingPostList(),//充电桩
            'inspectionInfo' => $this->getInspectionInfo(),
            'specialInfo' => $this->getSpecialInfo(),
        ];

        return $param;
    }


    public function getMotorJointType()
    {
        $demo = new VehicleAndCustomerInfoConfirmRequest();
        return $demo->getCoverageType($this->visitor->getCoverageVisitorList());
    }

    public function getBasePartReq()
    {
        $extInfo = $this->visitor->getExtInfoVisitor();
        $arr = [
            "jqEffectiveDate" => $this->visitor->ciStartData,
            "jqExpireDate" => $this->visitor->ciEndData,
            "jqImmeffMrk" => strval(intval($this->visitor->ciEffectFlag)),
            "syEffectiveDate" => $this->visitor->biStartData,
            "syExpireDate" => $this->visitor->biEndData,
            "syImmeffMrk" => strval(intval($this->visitor->biEffectFlag)),
            "syExpectedFloatingRate" => $extInfo->expectedDiscount,//期望折扣
            "fixedDropDiscount" => "0",//商业折扣是否下浮标志
            "jqProdNo" => "0320",
            "syProdNo" => $this->visitor->isNewEnergy ? "0358" : "0356",//商业险编码 0358新能源
            "finType" => $this->visitor->getExtInfoVisitor()->argc['finType'] ?? '',//收费方式
            "consultPurchaseValue" => $this->visitor->getVehicleVisitor()->actualValue,//协商实际价值
            "remark" => ""
        ];
        if($arr['syImmeffMrk']){
            $arr['syExpireDate'] = date('Y-m-d 23:59:59',strtotime($arr['syExpireDate']));
        }
        return $arr;
    }

    /**
     * 获取险种列表
     * @return array
     * @throws Exception
     */
    public function getCoverageList()
    {
        $coverageList = [];
        /*** @var PremiumCoverageVisitor $coverageVisitor */
        foreach ($this->visitor->getCoverageVisitorList() as $coverageVisitor) {
            if ($coverageVisitor->coverageCode == 'C01001') {
                continue;
            }
            $item = [
                "cvrgNo" => DAJIAEnums::$coverageCode[$coverageVisitor->coverageCode],
                "lossNAmt" => "",
                "lossNoPayAmt" => "",
                "lossNDeductionRate" => "",
                "lossDeductible" => "",
                "threeCIndemLmtLvl" => "",
                "threeNDeductionRate" => "",
                "threeNIndemLmt" => "",
                "carSscratchCIndemLmtLvl" => "",
                "driverNDeductionRate" => "",
                "passengerNDeductionRate" => "",
                "driverNLiabDaysLmt" => "",
                "passengerNLiabDaysLmt" => "",
                "passengerNPerAmt" => "",
                "therfNDeductionRate" => "",
                "therfNNAmt" => "",
                "deviceNAmt" => "",
                "repairDays" => "",
                "repairNAmt" => "",
                "medicalLiabilityNPerAmt" => "",
                "vehicleSafetyInspectionServices" => "",
                "inspectionServiceTimes" => "",
                "drivingServiceTimes" => "",
                "roadRescueServices" => "",
                "driverNPerAmt" => "",
                "passengerMoralDamageAmt" => "",
                "driverMedicalAmt" => "",
                "driverMoralDamageAmt" => "",
                "threeMoralDamageAmt" => "",
                "threeMedicalAmt" => "",
                "threeQuotaAmt" => "",
                "wheelAmt" => "",
                "gridFaultLossAmt" => "",
                "goodsLiabilityAmt" => ""
            ];
            if(in_array($coverageVisitor->coverageCode, ['C03005', 'C13005'])){
                if(!empty($coverageVisitor->deductionRate)){
                    $item['threeNDeductionRate'] = '-' . $coverageVisitor->deductionRate;//三者险 绝对免赔率
                }
            }
            if (in_array($coverageVisitor->coverageCode, ['C03001', 'C13001'])) {
                $item['threeCIndemLmtLvl'] = DAJIAEnums::$threeCIndemLmtLvl[$coverageVisitor->amount] ?? 0;//第三者责任险限额档次
                $item['threeNIndemLmt'] = $coverageVisitor->amount;//限额对应金额
                if(!empty($coverageVisitor->deductionRate)){
                    $item['threeNDeductionRate'] = '-' . $coverageVisitor->deductionRate;//绝对免赔率
                }
                if (empty($item['threeCIndemLmtLvl'])) {
                    throw new Exception("不支持的第三者责任险金额：" . $coverageVisitor->amount);
                }
            } elseif (in_array($coverageVisitor->coverageCode, ['C04001', 'C14001'])) {
//                $item['driverNDeductionRate'] = '-' . $coverageVisitor->deductionRate;//绝对免赔率
                $item['driverNLiabDaysLmt'] = 1;
                $item['driverNPerAmt'] = $coverageVisitor->amount;
            } elseif (in_array($coverageVisitor->coverageCode, ['C05001', 'C15001'])) {
//                $item['passengerNDeductionRate'] = '-' . $coverageVisitor->deductionRate;//绝对免赔率
                $item['passengerNLiabDaysLmt'] = $this->visitor->getVehicleVisitor()->vehicleSeat - 1;
                $item['passengerNPerAmt'] = $coverageVisitor->unitAmount;//单个乘客保额
            } elseif (in_array($coverageVisitor->coverageCode, ['C02001', 'C12001'])) {
                $item['lossNAmt'] = $this->visitor->getVehicleVisitor()->actualValue;//车损险保额
                $item['lossNoPayAmt'] = '375001';//免赔额为0
//                $item['lossNDeductionRate'] = '-' . $coverageVisitor->deductionRate;//绝对免赔率
            } elseif (in_array($coverageVisitor->coverageCode, ['C08001', 'C18001'])) {
                $item['roadRescueServices'] = $coverageVisitor->serviceTimes;//到路救援次数
            } elseif (in_array($coverageVisitor->coverageCode, ['C08002', 'C18002'])) {
                $item['vehicleSafetyInspectionServices'] = $coverageVisitor->serviceTimes;//安全检测次数
            } elseif (in_array($coverageVisitor->coverageCode, ['C08003', 'C18003'])) {
                $item['drivingServiceTimes'] = $coverageVisitor->serviceTimes;//代驾次数
            } elseif (in_array($coverageVisitor->coverageCode, ['C08004', 'C18004'])) {
                $item['inspectionServiceTimes'] = $coverageVisitor->serviceTimes;//送检次数
            } elseif (in_array($coverageVisitor->coverageCode, ['C02002', 'C12002'])) {
                $item['carSscratchCIndemLmtLvl'] = DAJIAEnums::$scratchLimit[$coverageVisitor->amount];//划痕险保额
            } elseif (in_array($coverageVisitor->coverageCode, ['C02007', 'C12007'])) {
                $item['deviceNAmt'] = $coverageVisitor->amount;//新增设备险保额
            } elseif (in_array($coverageVisitor->coverageCode, ['C02003', 'C12003'])) {
                $item['repairDays'] = $coverageVisitor->quantity;//修理天数
                $item['repairNAmt'] = $coverageVisitor->unitAmount;//每日保额
            } elseif (in_array($coverageVisitor->coverageCode, ['C05003', 'C15003'])) {
                $item['medicalLiabilityNPerAmt'] = $coverageVisitor->amount;//医疗保额（乘客） todo 金额字段不知道用哪个
                $item['passengerNLiabDaysLmt'] = $this->visitor->getVehicleVisitor()->vehicleSeat - 1;
            } elseif (in_array($coverageVisitor->coverageCode, ['C05002', 'C15002'])) {
                $item['passengerMoralDamageAmt'] = $coverageVisitor->amount;//【车上责任保险（乘客）】附加精神损害抚慰金责任险
            } elseif (in_array($coverageVisitor->coverageCode, ['C04003', 'C14003'])) {
                $item['driverMedicalAmt'] = $coverageVisitor->amount;//【车上人员责任保险（司机）】附加医保外医疗费用责任险
            } elseif (in_array($coverageVisitor->coverageCode, ['C04002', 'C14002'])) {
                $item['driverMoralDamageAmt'] = $coverageVisitor->amount;//【车上人员责任保险（司机）】附加精神损害抚慰金责任险
            } elseif (in_array($coverageVisitor->coverageCode, ['C03003', 'C13003'])) {
                $item['threeMoralDamageAmt'] = $coverageVisitor->amount;//【第三者责任保险】附加精神损害抚慰金责任险
            } elseif (in_array($coverageVisitor->coverageCode, ['C03004', 'C13004'])) {
                $item['threeMedicalAmt'] = $coverageVisitor->amount;//【第三者责任保险】附加医保外医疗费用责任险
            } elseif (in_array($coverageVisitor->coverageCode, ['C03002', 'C13002'])) {
                $item['threeQuotaAmt'] = $coverageVisitor->amount;//附加法定节假日限额翻倍险
            } elseif (in_array($coverageVisitor->coverageCode, ['C02004', 'C12004'])) {
                $item['wheelAmt'] = $coverageVisitor->amount;//附加车轮单独损失险
            } elseif ($coverageVisitor->coverageCode == 'C16001') {
                $item['gridFaultLossAmt'] = $coverageVisitor->amount;//附加外部电网故障损失险
            } elseif (in_array($coverageVisitor->coverageCode, ['C02008', 'C12008'])) {
                $item['goodsLiabilityAmt'] = $coverageVisitor->amount;//附加车上货物责任险
            }

            $coverageList[] = $item;
        }

        return $coverageList;
    }

    /**
     * 获取车船税
     * @return array
     */
    public function getVehicleTaxation()
    {
        $taxVisitor = $this->visitor->getCarTaxVisitor();
        $taxData = [
            "taxPaytaxTyp" => DAJIAEnums::$taxTypeCode[$taxVisitor->taxTypeCode],
            "taxEffBgnTm" => $taxVisitor->taxStartDate,
            "taxEffEndTm" => $taxVisitor->taxEndDate,
            "taxTaxfreeVhltyp" => "",
            "taxFreeRedTaxWay" => "",
            "taxFreeRedTaxPro" => "",
            "taxAbateAmt" => "",
            "taxFreeCertNo" => "",
            "taxFreeRedTaxOrgCde" => "",
            "taxFreeTaxOrg" => "",
            "taxComTaxOrgCde" => "",
            "taxComTaxOrg" => "",
            "taxPaymentRecptNo" => "",
            "taxDocumentDate" => "",
            "taxPaidAreaCode" => "",
            "taxDeptNonlocal" => "",
            "taxdptVhltyp" => "",
            "taxTaxpayerId" => ""
        ];
        if ($taxVisitor->taxTypeCode == 'T04') {
            //减税
            $taxData['taxTaxfreeVhltyp'] = DAJIAEnums::$taxReductionReasonCode[$taxVisitor->taxReductionReasonCode];//减免税原因（平台）
            $taxData['taxFreeRedTaxWay'] = DAJIAEnums::$taxReductionCode[$taxVisitor->taxReductionCode];//减免税方案（平台）
            $taxData['taxFreeRedTaxPro'] = round($taxVisitor->taxFreeRate / 100, 2);//减免比例（平台）
            $taxData['taxAbateAmt'] = $taxVisitor->taxExemption;//减税金额（平台）
            $taxData['taxFreeCertNo'] = $taxVisitor->taxDocumentNumber;//减免税凭证号（平台）
            $taxData['taxFreeRedTaxOrgCde'] = $taxVisitor->taxDepartmentCode;//减税税务机关代码（平台）
        } elseif ($taxVisitor->taxTypeCode == 'T03') {
            $taxData['taxFreeTaxOrg'] = $taxVisitor->taxDepartment;//免税税务机关名称（平台）
        } elseif ($taxVisitor->taxTypeCode == 'T02') {
            //完税
            $taxData['taxComTaxOrgCde'] = $taxVisitor->taxDepartmentCode;//完税税务机关代码（平台）
            $taxData['taxComTaxOrg'] = $taxVisitor->taxDepartment;//完税税务机关名称（平台）
            $taxData['taxPaymentRecptNo'] = $taxVisitor->taxDocumentNumber;//完税凭证号（平台）
            $taxData['taxDocumentDate'] = $taxVisitor->taxDocumentDate;//完税凭证填发日期（平台）
            $taxData['taxPaidAreaCode'] = $taxVisitor->taxPaidAreaCode;//开具完税凭证地区代码（平台）
        }

        return $taxData;
    }

    public function getVehicleInfo()
    {

    }

    /**
     * 非车信息
     * @return
     */
    public function getNoCarInfo()
    {
        $noCarVisitor = $this->visitor->getNonCarInquiryVisitor();
        $list = [];
        /**
         * @var NonCarProductVisitor $value
         */
        foreach ($noCarVisitor->getNonCarList() as $value){
            foreach ($value->subCoverage as $val){
                $arr = [
                    'nvhlProdCode' => $value->productCode,//非车产品代码
                    'nvhlSchemeCode' => $value->planCode,//非车方案代码
                    'nvhlEffectiveDate' => $noCarVisitor->startData,//非车保险起期
                    'nvhlExpireDate' => $noCarVisitor->endData,//非车保险止期
                    'noVhlSum' => $value->insuredNum,//非车投保份数
                    'nvhlPrm' => $value->premium,//非车险每份保费
                    'nvhlSumPrm' => round($value->premium * $value->insuredNum,2),//非车险保费
                    'nvGoodsCode' => 'SP008',//非车商品号
                    'nvDutyRiskCode' => $val->subCode,//非车险别代码
                ];
                if(isset($list[$val->subCode])){
                    $list[$val->subCode]['nvhlPrm'] = round($val->premium + floatval($list[$val->subCode]['nvhlPrm']));
                    $list[$val->subCode]['nvhlSumPrm'] = round($arr['nvhlSumPrm'] + floatval($list[$val->subCode]['nvhlSumPrm']));
                }else{
                    $list[$val->subCode] = $arr;
                }
            }
        }
        return array_values($list);
    }

    public function getInspectionInfo()
    {
        $extInfo = $this->visitor->getExtInfoVisitor();
        $res = [
            "vehicleInspectionCde" => DAJIAEnums::$carCheckCode[$extInfo->carCheckCode],
            "vehicleInspectTm" => "",
            "vehicleInspectorNme" => "",
            "vehicleInspectRec" => "",
            "vehicleResvTxt1" => "",
            "damagedSite" => ""
        ];
        if ($extInfo->carCheckCode == 'CS3') {
            //已验
            $res['vehicleInspectTm'] = $extInfo->carCheckDate;//
            $res['vehicleInspectorNme'] = $extInfo->carChecker;//验车人
            $res['vehicleInspectRec'] = '382001';//验车结果, 全车完好无损，证车相符，年审合格
        } elseif ($extInfo->carCheckCode == 'CS2') {
            //免验车
            $res['vehicleResvTxt1'] = DAJIAEnums::$carCheckReasonKind[$extInfo->carCheckReasonKind];
        }
        return $res;
    }

    public function getSpecialInfo()
    {
        $vehicleInfo = $this->visitor->getVehicleVisitor();
        $coverageType = $this->getMotorJointType();
        $obj = new VehicleAndCustomerInfoConfirmRequest();
        $code = $obj->getCIVehicleCode($vehicleInfo->attachNature, $vehicleInfo->carKindCode, $vehicleInfo->causeType);
        //单交强险种类型
        $code = $vehicle['vehicleUsageCde'] = $obj->checkJqCode($coverageType, $code);
        return [
            "vehicleUsageCde" => $code,
            "busiServiceCode" => "",
            "staffCar" => ""
        ];
    }

    public function getChargingPostList()
    {
        $list = $this->visitor->getChargingPileVisitorList();
        $chargingList = [];

        /** @var PremiumChargingPileVisitor $val */
        foreach ($list as  $val) {
            $arr = [
                'chargingSeqNo' => $val->seqNo,
                'chargingPostType' => $val->chargingPileType,//充电桩型号
                'chargingPostCode' => $val->chargingPileCode,//充电桩编码
                'chargingPostAddress' => $val->chargingPileAddress,//充电桩地址
                'chargingPostAddressType' => DAJIAEnums::$chargingPileAddressType[$val->chargingPileAddressType],//充电桩安装地点类型
                'chargingPostKind' => DAJIAEnums::$chargingPileKind[$val->chargingPileKind],//充电桩种类
                'chargingPostYearLimit' => DAJIAEnums::$chargingPileYearLimit[$val->chargingPileYearLimit],//充电桩使用年限
                'chargingLossAmt' => $val->lossAmount,//【损失险】保额
                'chargingLiabilityAmt' => $val->liabilityAmount,//【责任险】保额
                'chargingCvrgFlag' => '',//投保险别标识

            ];
            if(!empty($arr['chargingLossAmt'])){
                $arr['chargingCvrgFlag'] = '1';
            }
            if(!empty($arr['chargingLiabilityAmt'])){
                $arr['chargingCvrgFlag'] = '2';
            }
            if(!empty($arr['chargingLossAmt']) && !empty($arr['chargingLiabilityAmt'])){
                $arr['chargingCvrgFlag'] = '3';
            }
            $chargingList[] = $arr;
        }
        return $chargingList;
    }

}
